%matplotlib inline
import cv2
import os
import matplotlib.pyplot as plt
import numpy as np
from math import *
print os.listdir(".")
img = cv2.imread('1246431420.91.jpg')
# print img
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.show()
def displayImg(img):
img2 = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.imshow(img2)
plt.show()
def bb(img):
# img = cv2.resize(img,(500,500))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_OTSU)
contours,hier = cv2.findContours(thresh,cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:]
for cnt in contours:
if cv2.contourArea(cnt) > 1000 and cv2.contourArea(cnt) < 10000: # remove small areas like noise etc
hull = cv2.convexHull(cnt) # find the convex hull of contour
hull = cv2.approxPolyDP(hull,0.1*cv2.arcLength(hull,True),True)
if len(hull)==4:
# cv2.drawContours(img,[hull],0,(0,255,0),2)
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
# img = cv2.drawContours(img,[box],0,(0,0,255),2)
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
displayImg(img[y:y+h,x:x+w])
plt.imshow(img)
plt.show()
for path in os.listdir("."):
if("jpg" in path):
bb(cv2.imread(path))